 <?php
  //公共模块
 header("Content-type: text/html; charset=utf-8");
  class commonMod
    {
    public $model;//数据库模型对象
    public $tpl;//模板对象
    public $config;//全局配置
    static $global;//静态变量，用来实现单例模式
    public function __construct()
    {
    	//开启session
    	if(!isset($_SESSION))
    		session_start();
    		
    	date_default_timezone_set("Asia/Shanghai");
	    global $config;
	    $this->config=$config;//配置
	    //数据库模型初始化
	    if(!isset(self::$global['model']))
	    {
	    self::$global['model']=new cpModel($this->config);//实例化数据库模型类
	    }
	    $this->model=self::$global['model'];//数据库模型对象	
	  //  if(strpos($_SERVER["REQUEST_URI"],'port/')){	    	
    	//}else {	
		    //模板初始化
		    if(!isset(self::$global['tpl']))
		    {
		    self::$global['tpl']=new cpTemplate($this->config);//实例化模板类
		    }
		    $this->tpl=self::$global['tpl'];//模板类对象
		    if(strpos($_SERVER["REQUEST_URI"],'port/')){
	    	
    		}else {
	    		//验证是否登录
//		    	$uname = $_SESSION['manage_uname'];
//		    	$login = $_GET[login];
//                if($login!=2){//正在登录
//                    if($uname==''){
//                        if($login!=1){//不是登录页面则跳到登录页面
//                            $this->redirect(__APP__."/index?login=1");
//                        }
//                    }else{
//                        $this->assign('uname', $uname);
//                    }
//                }

    		}  
    	//}
    	//用户权限
    	/*$admin_groupid = $_SESSION['admin_groupid'];
    	 $this->assign('admin_groupid', $admin_groupid); */
		 
		 $admin_permission=$_SESSION['manage_permission'];

		 $this->assign('admin_permission', $admin_permission);

        $hotelrow = $this->model->table('d_config')->where("name='hotel_username'")->find();
        if($hotelrow){
            $this->assign('hotelName', $hotelrow['config']);
        }
    }
    //模板变量解析
    protected function assign($name, $value)
    {
    	return $this->tpl->assign($name, $value);
    }
    //模板输出
    protected function display($tpl='')
    {
    return $this->tpl->display($tpl);
    }

    //直接跳转
    protected function redirect($url)
    {
    header('location:'.$url,false,301);
    exit;
    }
    //操作成功之后跳转,默认三秒钟跳转
	protected   function success($msg,$url=NULL,$waitSecond=3)
	{
		if($url==NULL)
			$url=__URL__;
		$this->assign('message',$msg);
		$this->assign('url',$url);
		$this->assign('waitSecond',$waitSecond);
		$this->display('success');
		exit;
	}

    //出错之后跳转，后退到前一页
    protected function error($msg)
    {
    header("Content-type: text/html; charset=utf-8");
    $msg="alert('$msg');";
    echo "<script>$msg history.go(-1);</script>";
    exit;
    }
    
    
    /*
    功能:分页
    $url，基准网址，若为空，将会自动获取，不建议设置为空
    $total，信息总条数
    $perpage，每页显示行数
    $pagebarnum，分页栏每页显示的页数
    $mode，显示风格，参数可为整数1，2，3，4任意一个
    */
    protected function page($url,$total,$perpage=10,$pagebarnum=5,$mode=1)
    {
    $page=new page();
    return $page->show($url,$total,$perpage,$pagebarnum,$mode);
    }
    //文件上传测试
	protected function _upload($upload_dir)
    {
		
		$upload = new UploadFile();
		//设置上传文件大小
		$upload->maxSize=1024*1024*200;//最大200M
		//设置上传文件类型
		$upload->allowExts  = explode(',','jpg,gif,png,bmp');
	
		//设置附件上传目录
		$upload->savePath =CP_UPLOAD.$upload_dir."/";
		$upload->saveRule = cp_uniqid;
		if(!$upload->upload())
		 {
			//捕获上传异常
			$this->error($upload->getErrorMsg());
		}
		else 
		{
			//取得成功上传的文件信息
			return $upload->getUploadFileInfo();
		}
	}
    //数据是否存在查询
	public function search_already($tname,$name,$table){
		 $sql = 'select * from '.$table." where ".$tname."='".$name."'";
		 $row  =   $this->model->query($sql);
		 if($row){
		 	return 1;
		 }else{
		 	return 0;
		 }
	}
    //传入字段、表、数据，返回该数据ID
	public function search_id($ziduan,$shuju,$table){
		 $sql = 'select id from '.$table." where ".$ziduan."='".$shuju."'";
		 $row  =   $this->model->query($sql);
		 if($row){
		 	return $row[0]['id'];
		 }else{
		 	return 0;
		 }
	}
	
	//传入ID，字段，表，获取字段值
	public function search_name($ziduan,$id,$table){
		 $sql = 'select '.$ziduan.' from '.$table." where id='".$id."'";
		 $row  =   $this->model->query($sql);
		 if($row){
		 	return $row[0][$ziduan];
		 }else{
		 	return 0;
		 }
	}
	//传人房间名，获取房间状态
	public function ifRooms($name){
		 $sql = "select rstate,id from h_rooms where rname='".$name."'";
		 $row  =   $this->model->query($sql);
		 if($row){
		 	return $row[0][rstate];
		 }else{
		 	return 1;
		 }
	}
	//传人房间名，修改房间状态
	public function upRooms($name,$state){
		$sql = "update h_rooms set rstate=".$state." where rname = '".$name."'";		
		$this->model->query($sql);
	}
	
	//获取团队信息
	public function getTeamInfo(){
		$sql = "select name from h_team ";
		$row = $this->model->query($sql);
		if($row){
			return $row;
		}else{
			return 0;
		}
	}

	//传进图片id,删除图片
	public function delPicInfo($val){
		//删除原先图片
    	$sql = "select * from h_pic where id=".$val;
    	$row = $this->model->query($sql);
    	$picadd =  $row[0][picadd];
    	$str  = iconv("utf-8","gb2312",$picadd);
    	//查询图片是否存在
		if(file_exists('./'.$str)){
			unlink('./'.$str);	
		}
		//删除数据
		$sql = "delete from h_pic where id=".$val;
		$row = $this->model->query($sql);	
	}
	
    
	//传进电影id,删除电影
	public function delMovieInfo($val){
		//删除海报
    	$sql = "select * from h_movie where id=".$val;
    	$row = $this->model->query($sql);
		$str =  $row[0][adpic];
		$str1 =  $row[0][thumb];
    	if($str){
    		$str = iconv("utf-8","gb2312",$str);
	    	//查询图片是否存在
			if(file_exists('./'.$str)){
				unlink('./'.$str);	
			}
    	}
		if($str1){
    		$str = iconv("utf-8","gb2312",$str1);
	    	//查询图片是否存在
			if(file_exists('./'.$str)){
				unlink('./'.$str);	
			}
    	}	
		$sql = "delete from h_movie where id=".$val;
		$row = $this->model->query($sql);			
	}
	
	//传进电影id,删除电影
	public function delXinxiInfo($val){
		//删除海报
    	$sql = "select * from h_xinxi where id=".$val;
    	$row = $this->model->query($sql);
		$str =  $row[0][adpic];
		$str1 =  $row[0][thumb];
    	if($str){
    		$str = iconv("utf-8","gb2312",$str);
	    	//查询图片是否存在
			if(file_exists('./'.$str)){
				unlink('./'.$str);	
			}
    	}
		if($str1){
    		$str = iconv("utf-8","gb2312",$str1);
	    	//查询图片是否存在
			if(file_exists('./'.$str)){
				unlink('./'.$str);	
			}
    	}	
		$sql = "delete from h_xinxi where id=".$val;
		$row = $this->model->query($sql);			
	}
	//传进客人ID,查询是否为VIP，如果是删除VIP
	public function vipDel($gid){
		$sql = "select w.id from h_welcome w left join h_guest g on w.rname=g.rname where g.id=".$gid;
		$row = $this->model->query($sql);
		if($row){
			$sql = "delete from h_welcome where id=".$row[0][id];
			$this->model->query($sql);
		}
	}
	
	//删除有关此房间的其他信息如订餐，账单,消息
	public function delRoomInfo($id){
		/*
	    $sql="update  h_rate set state = 0 where  gid='".$id."'";
	    $row = $this->model->query($sql);
		  
	    $sql = "select name,rname from h_guest where id='".$id."'";
	    $row = $this->model->query($sql);
	    if ($row){
	    	$rname = $row[0][rname];
	    	$name = $row[0][name];
	    	echo $rname;
	    }else {
	    	$rname = '无人';
	    }
	    
		$sql="select boxid from h_rooms where rname='".$rname."'";
		$row = $this->model->query($sql);
		if($row){
			 $roomid=$row[0][boxid];
		}
		
		$sql = "select count(*) as krzs from h_guest  where  name='".$name."'";
		$row = $this->model->query($sql);
		if($row){
			 $krzs=$row[0][krzs];
			 if ($krzs == 1){
			 	echo "只有一个";
			 	$sql="delete from h_addinfo where rname=(select * from h_rooms where boxid='".$roomid."'";
				$row=$this->model->query($sql);
				
				$sql="select * from h_order where roomid='".$roomid."'";
				$row=$this->model->query($sql);
				if ($row){
					$ordernum=$row[0][ordernum];
					$sql="delete from h_buycar where oid='".$ordernum."'";
					$this->model->query($sql);
					$sql="delete from h_order where ordernum='".$ordernum."'";
					$this->model->query($sql);
				}
			 }else{
			 	echo "好几个";
			 }
		}
		*/
		
	}	
	//删除以房间号做客人名称所开的房间里的客人信息
	public function deleterooms($rname){
		$sql="delete from h_guest where name='".$rname."'";
		$this->model->query($sql);
	}
	
	//记录首页的来源地址
    public function rememberIndexNums(){
    	$nmcur  =  $_POST['nmcur'];
        $nocur  =  $_POST['nocur'];
    	$_SESSION['mcur'] = $nmcur;
    	$_SESSION['ocur'] = $nocur;
    	file_put_contents("test11.txt",$nmcur);
		exit;
    }
	
	public function addStaffLog($staff,$instruction,$type){
		$uname = $_SESSION['manage_uname'];
		$time =date('Y-m-d H:i:s',time()) ;
		$this->model->query("insert into h_stafflog (uname,operate,time, `instruction`, `role`) values ('{$uname}','{$staff}','{$time}','{$instruction}','{$type}')");
	}	
	/**
	 * sendMessage2room
	 * send messages to rooms
	 * @rooms room lists array
	 * @msgcontent message content. this should be json formatted
	 * @return 
	 * 0 success
	 * 1 failed
	 * echo error information to browser
	 **/
	public function sendMessage2room( $rooms, $msgcontent) {
		$server_port = 1234;
		$iplists = array();
		$falg = 0;
		if ( is_array( $rooms) ) {
			foreach ($rooms as $room) {
				$results = $this->model->table('h_rooms')->field('ipaddr')->where("`boxid` = '$room'")->select();
				foreach ( $results as $result ) {
					if ( $result['ipaddr'] ) {
						array_push($iplists, $result['ipaddr']);
					}
				}
			}
			foreach ( $iplists as $server_addr) {
				$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
				if ( $socket === false ) {
					//echo "发送错误";
					return 1;
				} 

				$result = socket_connect($socket, $server_addr, $server_port);
				if ( $result === false ) {
					//echo "连接$boxid失败";
					return 1;
				}

				socket_write($socket, $msgcontent, strlen($msgcontent));
				socket_close($socket);
			}
		}
		return 0;
	}

      //查询该用户是否是统计权限，统计数据按分组筛选显示
      public function isSpecialAdmin(){
          $permissionid=$_SESSION['manage_groupid'];
          $row=   $this->model->query("SELECT * FROM `h_permission` WHERE id=".$permissionid." and rolename='统计'");
          $hotelGroupid=0;
          if($row){
              $uid=$_SESSION['manage_uid'];
              $rowGroup=   $this->model->query("SELECT * FROM `h_hotelsid_adminid` WHERE `adminId`=".$uid);
              if($rowGroup){
                  $hotelGroupid=1;
              }
          }
          return $hotelGroupid;
      }

      //获取子菜单目录
      public function getChindMenu($lable){
          $list = $this->model->query( "SELECT mc.*,mp.menuLabel as pmenuLabel FROM `h_navigation_menu` mc left join h_navigation_menu mp on mc.pid=mp.id WHERE mc.state=1 and mp.state=1 and  mp.`menuLabel`='{$lable}'");
          return $list;
      }

      public function getPage($countPage,$count){
          require(CP_PATH.'ext/Page.class.php');
          //获取页数ID
          $page_id=intval($_GET['page']);

          $url=__URL__.'/page?page='.$page_id;
          $page=new Page();
          //每页显示行数
          $listRows=$countPage;//每页显示的信息条数
          //每页显示页数
          $pageBarNum=5;
          $cur_page=$page->getCurPage($url);

          $limit_start=($cur_page-1)*$listRows;
          $limit=$limit_start.','.$listRows;
          $limitStr='';
          if($limit!=''){
              $limitStr = " limit ".$limit;
          }

          if($listRows>=$count){
              $this->assign('page','');
          }else{
              $htmPage =  $page-> show($url,$count,$listRows,$pageBarNum,$mode=5);
              $this->assign('page', $htmPage);
          }
          return $limitStr;
	  }

  }
 ?>
 
 
 
 
 
